<?php
/**
 * Project: Vietsam
 * Package Controller
 * Class: Register
 * Author: Hung Nguyen		email: quochungndvt88@yahoo.com
 * Created on Fer 8, 2012
 * Updated on Fer 30, 2012
 *
 * */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Customer extends MY_Controller {

     function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->library('parser');
        $this->load->helper(array('form', 'url'));
        $this->load->helper('date');
        $this->load->library('email');
        $this->load->model('customer_model','customer');
        $this->load->model('country_model','country');
        $this->template->add_region('new_tours');
        $this->buildNavigation();
//        $this->buildAccountBox();
        
		//$this->buildSearchByConditionBox();
//		$this->buildSupportBox();
		//$this->buildAdvBox();
		//$this->buildSlider();
		//$this->buildCartBox();
		//$this->buildCompareBox();
        
     }

    function index() {
    	if($this->checkUserLogin()){
    		$this->buildAccountBox();
    		$this->buildSupportBox();
    		$data['base_url'] = base_url();
	    	//$this->fn_build_menu_left();
	        $this->template->parse_view('right_content2column', $this->skins.'customer/dashboard_view', $data);
			$this->template->render();
    		
    	}else{
    		redirect("auth");
    	}
    }
    /*function view(){
    	$data['base_url'] = base_url();
    	$this->fn_build_menu_left();
        $this->template->parse_view('center_content1', $this->skins.'customer/view', $data);
		$this->template->render();
    }*/
	function add() {
		if($this->checkUserLogin())
			redirect("customer/update");
    	$error_message = '';
	      if(isset($_POST['profile_add']))
	      {
	      	$this->fn_save_post_data('profile');
	      	$profile = $this->input->post('profile');
	      	$email = trim($profile['email']);
	        $password = trim($profile['password']);
	        $password_conf = trim($profile['password_conf']);
	        $firstname = trim($profile['firstname']);
	        $lastname = trim($profile['lastname']);
	        $error = false;
	        if ($email == '') {
	            $error = true;
	            $error_message .= $this->lang->line('email_is_required') . '<br>';
	        } else {
	            $this->load->helper('email');
	            if (!valid_email($email)) {
	                $error = true;
	                $error_message .= $this->lang->line('email_is_invalid') . '<br>';
	            }
	        }
	
	        if ($password == '' || $password_conf == '') {
	            $error = true;
	            $error_message .= $this->lang->line('password_is_required') . '<br>';
	        }elseif($password !== $password_conf){
	        	$error = true;
	            $error_message .= $this->lang->line('password_confirm_not_match') . '<br>';
	        
	        }
	        if($firstname == ''){
	        	$error = true;
	        	$error_message .= $this->lang->line('firstname_is_required') . '<br>';
	        }
	       if($lastname == ''){
	        	$error = true;
	        	$error_message .= $this->lang->line('lastname_is_required') . '<br>';
	        }
	
	        if (!$error) {   
	        	$this->load->helper('string'); 
				$profile['last_password_gen'] = unix_to_human(now(), TRUE, 'us');
				$profile['salt'] = $this->fn_generate_salt();
				$profile['password'] = md5($password); //$this->fn_generate_salted_password($password, $profile['salt']);
				$profile['active_key'] = random_string('alnum', 16); //$this->active_key($email);
				$user_id = $this->customer->create_account($profile);
				if($user_id == -1){
					$error_message = $this->lang->line('exist_email');
					$data['post_data'] = $this->fn_get_post_data("profile");
				}elseif($user_id){
					
					//$data['active_link'] = $this->send_activation_key($email, $profile['active_key']);
					$data['hide_register_form'] = true;//hide form register
					//ok done send email
					$message = 'Thanks for register '."<br />";
					$message .= 'Your first name: '. $profile['firstname'] ."<br />";
					$message .= 'Your last name: '. $profile['lastname'] ."<br />";
					$message .='Your email: '.$profile['email']."<br />";
					//$message.= 'Your password: ' . $password ."<br />";
					$message .= 'Please click <a href="'.site_url('auth').'" target="_blank" >here</a> to active your account.';
					if($this->send_email($profile['email'], $message, "Account information")){
						$error_message = $this->lang->line('create_account_success');
					}
				}
	        }else{
	        	$data['post_data'] = $this->fn_get_post_data("profile");
	        }
	        
	      }
			$data['error_message'] = $error_message;
        	$data['site_url'] = site_url();
            $this->template->parse_view('center_content1', $this->skins.'customer/add', $data);
			$this->template->render();
	      
      
    }
    
    function register(){
    	if($this->checkUserLogin())
			redirect("customer/update");
			
    	$error_message = '';
    	$data = array();
    	$data['error_message'] = '';
    	$data['firstname'] = '';
    	$data['lastname'] = '';
    	$data[''] = '';
    	
    	
	      if(isset($_POST['profile_add']))
	      {
	      	$data = $this->input->post();
	      	$data['error_message'] = '';	
			$this->load->library('form_validation');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
			$this->form_validation->set_rules('lastname', 'lang:lastname', 'required|min_length[2]|max_length[50]');
			$this->form_validation->set_rules('firstname', 'lang:firstname', 'required|min_length[2]|max_length[50]');
			$this->form_validation->set_rules('password', 'lang:password', 'required|min_length[6]|max_length[20]');
			$this->form_validation->set_rules('password_conf', 'Confirm password', 'required|matches[password]');
	      	
	      	if ($this->form_validation->run() == FALSE) {
				$data['error_message'] = '<div id="error" style="color:red">' . validation_errors() . '</div>';
			}
			else{
				$this->load->helper('string'); 
				$profile = $data; //$this->input->post();
				$profile['last_password_gen'] = unix_to_human(now(), TRUE, 'us');
				$profile['salt'] = $this->fn_generate_salt();
				$profile['password'] = md5(trim($profile['password'])); //$this->fn_generate_salted_password($password, $profile['salt']);
				$profile['active_key'] = random_string('alnum', 32); //$this->active_key($email);
				$user_id = $this->customer->create_account($profile);
				if($user_id == -1){
					$data['error_message'] = '<div id="error" style="color:red">' . $this->lang->line('exist_email') . '</div>';
					//$data['post_data'] = $this->fn_get_post_data("profile");
				}elseif($user_id){
					$profile['id_user'] = $user_id;
					$profile['profile_type'] = 'P';
					$this->load->model('register_user_profiles_model','profile_model');
					$this->profile_model->create($profile);
					//$data['active_link'] = $this->send_activation_key($email, $profile['active_key']);
					$data['hide_register_form'] = true;//hide form register
					//ok done send email
					$message = 'Thanks for register '."<br />";
					$message .= 'Your first name: '. $profile['firstname'] ."<br />";
					$message .= 'Your last name: '. $profile['lastname'] ."<br />";
					$message .='Your email: '.$profile['email']."<br />";
//					$message.= 'Your password: ' . $password ."<br />";
					$message .= 'Please click <a href="'.site_url('customer/active/'. $profile['email'] . '/' .  $profile['active_key']).'" target="_blank" >here</a> to active your account.';
					if($this->send_email($profile['email'], $message, "Account information")){
						$error_message = $this->lang->line('create_account_success');
					}
					
					$data['title'] = lang('register_account_success');
					$data['message'] = sprintf(lang('messgae_register_account_success'), $profile['email'], $profile['email']);
					$this->template->parse_view('full_content1', $this->skins.'customer/message_view', $data);
					$this->template->render();
					return ;
				}
				
				//redirect('auth/login');
			}
			
	      }
//			$data['error_message'] = ''; //'<div id="error">' . $error_message . '</div>';
//        	$data['site_url'] = site_url();
//            $this->template->parse_view('center_content1', $this->skins.'customer/add', $data);
//			$this->template->render();

//			$data['base_url'] = base_url();
	    	//$this->fn_build_menu_left();
//	        $this->template->parse_view('right_content2column', $this->skins.'customer/register_view', $data);
//			$this->template->render();
			
//			$data['error_message'] = $error_message;
        	$data['base_url'] = base_url();
        	$this->template->parse_view('full_content1', $this->skins."customer/register_view", $data);
			$this->template->render();
    }
    
	function email_check($email) {
		$this->load->model('customer_model', 'customer', true);
		$result = $this->customer->getByEmail($email);
				
        //$result = $this->product->getByCode($code);
        if ($result != null) {
            $this->form_validation->set_message('email_check', '%s is not available.');
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
    function contacts($profile_id=null){

    	if($this->checkUserLogin()){

    		$user_data = array();
    		$this->fn_parse_array($user_data, $this->session->userdata("customer"));
	    	$error_message ='';
	    	
	    	if(isset($_POST['btnAddContacts'])){
		    	$contacts = $this->input->post('contacts');
		    	
		    	$copy_address = $_POST['copy_address'];
		    	if($copy_address == 'Y'){
		    		$this->fn_copy_address($contacts);
		    		
		    	}
		    	$contacts['id_user'] = $user_data['id_user'];
		    	$contacts['multi_profile'] = false;//allow to create multi profile
		    	if(!$this->customer->create_profile($contacts)){
		    		$error_message = $this->lang->line('add_contact_error');
		    	}else{
		    		$error_message = $this->lang->line('add_contact_success');
		    	}
	    	}
	    	$country = $this->country->getAll();
	    	$profile = $this->customer->get_profile($user_data['id_user'], $profile_id);
	    	if(!empty($profile)){
	    		$this->fn_parse_array($data, $profile);
	    		$data['update_profile'] = true;
	    		$data['lang_button_profile'] = $this->lang->line('update_contacts');
	    	}else{
	    		$data['lang_button_profile'] = $this->lang->line('add_contacts');
	    	}
	    	//$this->fn_print_r($user_data);
	    	
	    	$data['b_country_a'] = $this->fn_form_dropdown($country,$profile['b_country']);
	    	$data['s_country_a'] = $this->fn_form_dropdown($country,$profile['s_country']);
	    	$data['error_message'] = $error_message;
		    $data['base_url'] = base_url();
		    
	    	$this->template->parse_view('center_content1', $this->skins.'customer/contacts', $data);
			$this->template->render();
    	}else{
    		redirect("auth");
    	}
    }
    
    private function fn_copy_address(&$data){
    	if(is_array($data)){
    		$data_tmp = array();
    		
    		foreach($data as $k => $v){
    			if(strpos($k, "b_") !==false){
    				$data_tmp["s_".substr($k, 2)] = $v;
    			}
    		}
    		foreach ($data_tmp as $k => $v){
    			$data[$k] = $v;
    		}	
    	}
    }
    private function fn_build_menu_left(){
    	//$this->buildAccountBox();
    }
	
	function update() {
		if($this->checkUserLogin()){
			
			$error_message='';
			$user_data_session = $this->session->userdata('customer');
			$user_data_session_email = is_object($user_data_session) ? $user_data_session->email : $user_data_session['email'];
			$user_data = $this->customer->getByEmail($user_data_session_email);
		    $this->fn_parse_array($data, $user_data);
	    	if(isset($_POST['profile_update'])){
		      	
		      	$profile = $this->input->post('profile');
		      	$email = trim($profile['email']);
		        $password = trim($profile['password']);
		        $password_conf = trim($profile['password_conf']);
		        $firstname = trim($profile['firstname']);
		        $lastname = trim($profile['lastname']);
		        
		        $error = false;
		        if ($email == '') {
		            $error = true;
		            $error_message .= $this->lang->line('email_is_required') . '<br>';
		        } else {
		            $this->load->helper('email');
		            if (!valid_email($email)) {
		                $error = true;
		                $error_message .= $this->lang->line('email_is_invalid') . '<br>';
		            }
		        }
				if($password !== $password_conf){
		        	$error = true;
		            $error_message .= $this->lang->line('password_confirm_not_match') . '<br>';
		        
		        }
		        if($firstname == ''){
		        	$error = true;
		        	$error_message .= $this->lang->line('firstname_is_required') . '<br>';
		        }
		       if($lastname == ''){
		        	$error = true;
		        	$error_message .= $this->lang->line('lastname_is_required') . '<br>';
		        }
		
		        if (!$error) {
			        if(!empty($password) && !$this->fn_compare_login_password($user_data,$password)){
			        	//$this->fn_print_r($profile);exit();
			        	$profile['last_password_gen'] = unix_to_human(now(), TRUE, 'us');
	                    $profile['salt'] = $this->fn_generate_salt();
						$profile['password'] = $this->fn_generate_salted_password($password, $profile['salt']);
	                }
					$profile['id_user'] = $user_data->id_user;
					if($this->customer->update_account($profile)){
						
						//ok done send email
						$message = 'Your account has been updated '."<br />";
						$message .= 'Your first name: '. $profile['firstname'] ."<br />";
						$message .= 'Your last name: '. $profile['lastname'] ."<br />";
						$message .='Your email: '.$profile['email']."<br />";
						if($password !== ''){
							$message.= 'Your password: ' . $password ."<br />";
						}
						$message .= 'Please click <a href="'.base_url().'auth" target="_blank" >here</a> to login ';
						if($this->send_email($profile['email'], $message, "Account information")){
							$error_message = $this->lang->line('update_contact_success');
						}
						
					}else{
						$error_message = $this->lang->line('update_contact_error');
					}
					
		        }
		        
		    }
			$data['error_message'] = $error_message;
        	$data['base_url'] = base_url();
            $this->template->parse_view('center_content1', $this->skins.'customer/update', $data);
			$this->template->render();
			
		}else{
			redirect("auth");
		}
    }
    private function fn_form_dropdown($data,$selected = array(),$value='id',$name='name')
    {
    	$lang = "en_";
        if ( ! is_array($selected))
        {
            $selected = array($selected);
        }
        $extra = ' ';

        $multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';

        //$form = '<select name="'.$name.'"'.$extra.$multiple.">\n";
        $form = '';
        foreach ($data as $row){
            $sel = (in_array($row['id'], $selected))?' selected="selected"':'';
			$form .= '<option value="'.$row["{$value}"].'"'.$sel.'>'.$row["{$lang}{$name}"]."</option>\n";
        }
        
        return $form;
    } 
    
    private function active_key($str){
    	return $this->fn_generate_salted_password($str, $this->fn_generate_salt().$str);
    }
    
	function send_activation_key($user_email, $user_activation_key){
		$message = $this->body_email_active_key($user_email, $user_activation_key);
		$this->load->library('email');
    	$this->email->from('hung.nguyen@kns.com.vn', 'Quoc Hung');
		$this->email->to($user_email);
		//$this->email->cc('another@another-example.com');
		//$this->email->bcc('them@their-example.com');
		
		$this->email->subject('Active Account');
		$this->email->message($message);
		
		if($this->email->send())
		{
			//echo 'Email sent.';
			$this->email->clear();
			return true;
		}
		else
		{
			//show_error($this->email->print_debugger());
			return false;
		}
    	
   }
	function send_email($to, $message,$subject){
		$this->load->library('email');
    	$this->email->from('hung.nguyen@kns.com.vn', 'Quoc Hung');
		$this->email->to($to);
		//$this->email->cc('another@another-example.com');
		//$this->email->bcc('them@their-example.com');
		
		$this->email->subject($subject);
		$this->email->message($message);
		
		if($this->email->send())
		{
			//echo 'Email sent.';
			$this->email->clear();
			return true;
		}
		else
		{
			//show_error($this->email->print_debugger());
			return false;
		}
    	
   }
   private function body_email_active_key($email, $key){
   	$body = '<a href="'.base_url().'customer/active?email='.$email.'&key='.$key.'" target="_blank" >Please click here to active your account.</a>';
   	return $body;
   }
   
	function province($data=1,$type='b',$select=0){
		$type = trim($type);
		if($type != 'b'){
			$type= 's';
		}
    	$province = $this->country->getProvince($data,$select);
    	if(!empty($province)){
	    	$province_text = $this->fn_form_dropdown($province);
	    	$province_text = '<select id="'.$type.'_contacts_state" name="contacts['.$type.'_state]" >'.$province_text.'</select>';
    	}else{
    		$province_text = '<input type="text" name="contacts['.$type.'_state]" id="'.$type.'_contacts_state" class="input-text" value=""/>';
    	}
    	$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($province_text));
    	
    }
    
    function active($email, $key){
    	$error_message='';
    	//if(!empty()($_GET['email']) && isset($_GET['key'])){
//    		$email = trim($_GET['email']);
//    		$key = trim($_GET['key']);
    		$active_key = $this->customer->get_active_key_by_email($email);
    		//$this->fn_print_r($active_key);exit();
    		if(!empty($active_key) && $active_key->active_key == trim($key)){
    			$this->customer->active_user($email);
    				//$error_message .= $this->lang->line('active_account_success');
    				//$data['access_link'] = '<a href="'.base_url().'customer">Click here to manage your account.</a>';
    			
    			$message = sprintf( $this->lang->line('active_account_success'), site_url('member'));
    			//$data['access_link'] = '<a href="'.base_url().'customer">Click here to manage your account.</a>';
    		}
    		else{
    			$message = $this->lang->line('account_already_active');
    		}
    	//}
    	
    	/*
    	elseif(isset($_POST['email']) && isset($_POST['btn_resend_active_key'])){
    		$error = false;
    		$email = trim($_POST['email']);
    		if ($email == '') {
	            $error = true;
	            $error_message .= $this->lang->line('email_is_required') ;
	        }
	        if(!$error){
	        	//$data['active_link'] = $this->resend_active_key($email);
	        	
	    		$error_message .= $this->lang->line('resend_active_key_success');
	    		
	    	}
    	}elseif($this->session->userdata('active') === false){//account not activation
    		$error_message .= $this->lang->line('account_not_active');
    		$data['show_active_form'] = true;
    		$this->session->unset_userdata('active');
    	}
    	if(!empty($message) && $message == 0){//check if email not register.
    		unset($data);
    		$error_message = $this->lang->line('account_not_register');
    		
    	}
    	*/
    	
//    	$data['error_message'] = $error_message;
//        $data['base_url'] = base_url();
//        $this->template->parse_view('center_content1', $this->skins.'customer/active', $data);
//		$this->template->render();
		
		$data['title'] = lang('active_account');
		$data['message'] = $message;
		$this->template->parse_view('full_content1', $this->skins.'customer/message_view', $data);
		$this->template->render();
					
//		$data['base_url'] = base_url();
//        $this->template->parse_view('full_content1', $this->skins."customer/register_view", $data);
//		$this->template->render();
    }
    
    private function resend_active_key($email){
    	
		$user_data = $this->customer->getByEmail($email);
		if(empty($user_data)){
			//return user not register;
			redirect("customer/active/0");
		}
		$active_key = $this->active_key($email);
		$this->customer->update_active_key($email, $active_key);
		return $this->send_activation_key($email, $active_key);
    }
  
}

?>